﻿@model IEnumerable<Kooboo.CMS.Content.Models.WorkflowItem>
@{
    Layout = ViewBag.Layout ?? "~/Views/Shared/EditorTemplates/_TR.cshtml";

    var workflowItemJson = Newtonsoft.Json.JsonConvert.SerializeObject(new Kooboo.CMS.Content.Models.WorkflowItem());
    var modelJson = Model != null ? Newtonsoft.Json.JsonConvert.SerializeObject(Model) : "[]";
    var roleNamesJson = Newtonsoft.Json.JsonConvert.SerializeObject((new Kooboo.CMS.Web.Areas.Contents.Models.DataSources.RolesDatasource()).GetSelectListItems(ViewContext.RequestContext, ""));
}
<table id="workflowItems" class="key-value">
    <thead data-bind="visible: data().length>0">
        <tr>
            <th>
                @("Step name".Localize())
            </th>
            <th>
                @("Role name".Localize())
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody data-bind="foreach:{ data:data,afterRender:parseValidation}">
        <tr>
            <td>
                <input type="text" data-bind="value:DisplayName, attr: {name: $parent.getPrefixFieldName($index()) + 'DisplayName'}" class="medium" @Validator.Required().ClientValidationRule.GenerateHtmlAttributes()/>
                @Html.ValidationMessage("DisplayName", new RouteValueDictionary().Merge("data-bind", "attr: {'data-valmsg-for': $parent.getPrefixFieldName($index()) + 'DisplayName'}"))
            </td>
            <td>
                <select class="short" data-bind="value:RoleName,options: Roles, optionsText: 'Text', optionsValue: 'Value',  attr: {name: $parent.getPrefixFieldName($index()) + 'RoleName'}"></select>
            </td>
            <td>
                <a class="action" data-bind="click: $parent.removeItem">@Html.IconImage("minus")</a>

            </td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td><a class="action" data-bind="click: $data.addItem">@Html.IconImage("plus")</a></td>
        </tr>
    </tfoot>
</table>

<script type="text/javascript">
    $(function () {
        function WorkflowItemsViewModel() {
            var self = this;
            var roles = @Html.Raw(roleNamesJson);
            var bindRoles = function(item){
                item.Roles = ko.computed(function() {
                    return _.filter(roles,function(r){                       
                        return !_.any( self.data(),function(d){
                            return r.Value == d.RoleName();
                        }) || (r.Value == item.RoleName());
                    });
                }, item)
            };

            self.data = ko.mapping.fromJS(@Html.Raw(modelJson));

            _.each(self.data(),function(item){
                bindRoles(item);
            });
            
            self.addItem = function () {
                var item = ko.mapping.fromJS(@Html.Raw(workflowItemJson));
                bindRoles(item);
                if(item.Roles().length !=0){
                    self.data.push(item);     
                }
            };

            self.removeItem = function () {
                self.data.remove(this);                
            };

            var namePrfix = 'Items';
            self.getPrefixFieldName = function (index) {
                return namePrfix + '[' + (index) + '].';
            };

            self.parseValidation = function (element, index, data) {
                $.removeData($('form')[0], 'validator'); //remove validator for the form.
                $.validator.unobtrusive.parse('form');
            };

        }
        ko.applyBindings(new WorkflowItemsViewModel(), $("#workflowItems")[0]);
    });
</script>
